#!/usr/bin/perl -w

use strict;
use Time::Local;

my $frequency = 5 * 60;
$frequency = $ARGV[1] * 60 if (@ARGV > 1);

my $sample_date = 0;
my $sample_hour = 9;
my $sample_min = 0;
my $sample_clock = ($sample_hour * 60 + $sample_min ) * 60;

my @data;
open FILE, $ARGV[0] or die $!;
while (<FILE>) {
  chomp;
  my @fields = split /,/, $_;
  my $date = $fields[0] * 10000 + $fields[1] * 100 + $fields[2];
  my $clock = ($fields[3] * 60 + $fields[4]) * 60 + $fields[5];
  if ($sample_date != $date) {
    $sample_date = $date;
    $sample_clock = 9 * 60 * 60;
    $sample_clock += $frequency until ($sample_clock > $clock);
    $sample_hour = int($sample_clock / 3600);
    $sample_min = ($sample_clock - $sample_hour * 3600) / 60;
    my @tick = (@fields[0..2], $sample_hour, $sample_min, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    push @data, [@tick];
  }
  if ($sample_clock < $clock) {
    $sample_clock += $frequency;
    if ($sample_clock > (11 * 60 + 30) * 60) {
      $sample_clock += $frequency until ($sample_clock >= (13 * 60 + 30) * 60);
    }
    if ($sample_clock <= 15 * 60 * 60) {
      $sample_hour = int($sample_clock / 3600);
      $sample_min = ($sample_clock - $sample_hour * 3600) / 60;
      my @tick = (@fields[0..2], $sample_hour, $sample_min, 0, $data[-1][6], 0, @{$data[-1]}[8..13]);
      push @data, [@tick];
    }
  } else {
    $data[-1][6] = $fields[6];
    $data[-1][7] += $fields[7];
    splice @{$data[-1]}, 8, 6, @fields[8..13];
  }
}
close FILE;

foreach (@data) {
  print join(",", @{$_}), "\n";
}
